﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data;
using System.Data.OleDb;
using System.Collections;

namespace WebStudio.Framework.Helper
{
    /// <summary>
    /// Access数据库操作帮助
    /// </summary>
    public class AccessHelper
    {
        /// <summary>
        /// 数据库连接字符串
        /// </summary>
        public static readonly string ConnString;

        /// <summary>
        /// 参数缓存哈希表
        /// </summary>
        private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable());

        static AccessHelper()
        {
            ConnString = ConfigurationManager.ConnectionStrings["Default_Access"].ConnectionString;
                //+ AppDomain.CurrentDomain.BaseDirectory
                //+ ConfigurationManager.ConnectionStrings["DBPath"].ConnectionString;
        }

        #region 执行SQL语句
        /// <summary>
        /// 执行SQL语句
        /// </summary>
        /// <param name="connectionString">数据库连接字符串</param>
        /// <param name="cmdType">命令类型</param>
        /// <param name="cmdText">SQL语句</param>
        /// <param name="commandParameters">命令参数</param>
        /// <returns>执行成功条数</returns>
        public static int ExecuteNonQuery(string connectionString, CommandType cmdType, string cmdText, params OleDbParameter[] commandParameters)
        {
            OleDbCommand cmd = new OleDbCommand();

            using (OleDbConnection conn = new OleDbConnection(connectionString))
            {
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                int val = cmd.ExecuteNonQuery();
                cmd.Parameters.Clear();
                return val;
            }
        }

        /// <summary>
        /// 执行SQL语句
        /// </summary>
        /// <param name="cmdType">命令类型</param>
        /// <param name="cmdText">SQL语句</param>
        /// <param name="commandParameters">命令参数</param>
        /// <returns>执行成功条数</returns>
        public static int ExecuteNonQuery(CommandType cmdType, string cmdText, params OleDbParameter[] commandParameters)
        {
            return ExecuteNonQuery(ConnString, cmdType, cmdText, commandParameters);
        }

        /// <summary>
        /// 执行SQL语句
        /// </summary>
        /// <param name="connection">数据库连接</param>
        /// <param name="cmdType">命令类型</param>
        /// <param name="cmdText">SQL语句</param>
        /// <param name="commandParameters">命令参数</param>
        /// <returns>执行成功条数</returns>
        public static int ExecuteNonQuery(OleDbConnection connection, CommandType cmdType, string cmdText, params OleDbParameter[] commandParameters)
        {
            OleDbCommand cmd = new OleDbCommand();

            PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
            int val = cmd.ExecuteNonQuery();
            cmd.Parameters.Clear();
            return val;
        }

        /// <summary>
        /// 执行SQL语句
        /// </summary>
        /// <param name="trans">数据库事务</param>
        /// <param name="cmdType">命令类型</param>
        /// <param name="cmdText">SQL语句</param>
        /// <param name="commandParameters">命令参数</param>
        /// <returns>执行成功条数</returns>
        public static int ExecuteNonQuery(OleDbTransaction trans, CommandType cmdType, string cmdText, params OleDbParameter[] commandParameters)
        {
            OleDbCommand cmd = new OleDbCommand();
            PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, commandParameters);
            int val = cmd.ExecuteNonQuery();
            cmd.Parameters.Clear();
            return val;
        }

        #endregion

        #region 获取字段值

        /// <summary>
        /// 获取字段值
        /// </summary>
        /// <param name="connectionString">数据库连接字符串</param>
        /// <param name="cmdType">命令类型</param>
        /// <param name="cmdText">SQL语句</param>
        /// <param name="commandParameters">命令参数</param>
        /// <returns>字段值</returns>
        public static object ExecuteScalar(string connectionString, CommandType cmdType, string cmdText, params OleDbParameter[] commandParameters)
        {
            OleDbCommand cmd = new OleDbCommand();

            using (OleDbConnection connection = new OleDbConnection(connectionString))
            {
                PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
                object val = cmd.ExecuteScalar();
                cmd.Parameters.Clear();
                return val;
            }
        }

        /// <summary>
        /// 获取字段值
        /// </summary>
        /// <param name="cmdType">命令类型</param>
        /// <param name="cmdText">SQL语句</param>
        /// <param name="commandParameters">命令参数</param>
        /// <returns>字段值</returns>
        public static object ExecuteScalar(CommandType cmdType, string cmdText, params OleDbParameter[] commandParameters)
        {
            OleDbCommand cmd = new OleDbCommand();

            using (OleDbConnection connection = new OleDbConnection(ConnString))
            {
                PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
                object val = cmd.ExecuteScalar();
                cmd.Parameters.Clear();
                return val;
            }
        }

        /// <summary>
        /// 获取字段值
        /// </summary>
        /// <param name="connection">数据库连接</param>
        /// <param name="cmdType">命令类型</param>
        /// <param name="cmdText">SQL语句</param>
        /// <param name="commandParameters">命令参数</param>
        /// <returns>字段值</returns>
        public static object ExecuteScalar(OleDbConnection connection, CommandType cmdType, string cmdText, params OleDbParameter[] commandParameters)
        {
            OleDbCommand cmd = new OleDbCommand();

            PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
            object val = cmd.ExecuteScalar();
            cmd.Parameters.Clear();
            return val;
        }

        /// <summary>
        /// 获取字段值
        /// </summary>
        /// <param name="trans">数据库事务</param>
        /// <param name="cmdType">命令类型</param>
        /// <param name="cmdText">SQL语句</param>
        /// <param name="commandParameters">命令参数</param>
        /// <returns>字段值</returns>
        public static object ExecuteScalar(OleDbTransaction trans, CommandType cmdType, string cmdText, params OleDbParameter[] commandParameters)
        {
            OleDbCommand cmd = new OleDbCommand();
            PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, commandParameters);
            object val = cmd.ExecuteScalar();
            cmd.Parameters.Clear();

            return val;
        }

        #endregion

        #region 获取数据集
        /// <summary>
        /// 获取数据集 [DataReader]
        /// </summary>
        /// <param name="connectionString">数据库连接串</param>
        /// <param name="cmdType">命令类型</param>
        /// <param name="cmdText">SQL语句</param>
        /// <param name="commandParameters">命令参数</param>
        /// <returns>数据集</returns>
        public static OleDbDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params OleDbParameter[] commandParameters)
        {
            OleDbCommand cmd = new OleDbCommand();
            OleDbConnection conn = new OleDbConnection(connectionString);

            // we use a try/catch here because if the method throws an exception we want to 
            // close the connection throw code, because no datareader will exist, hence the 
            // commandBehaviour.CloseConnection will not work
            try
            {
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                OleDbDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Parameters.Clear();
                return rdr;
            }
            catch (Exception e)
            {
                conn.Close(); 
                return null;
            }
        }

        /// <summary>
        /// 获取数据集 [DataReader]
        /// </summary>
        /// <param name="connectionString">数据库连接串</param>
        /// <param name="cmdType">命令类型</param>
        /// <param name="cmdText">SQL语句</param>
        /// <param name="commandParameters">命令参数</param>
        /// <returns>数据集</returns>
        public static OleDbDataReader ExecuteReader(CommandType cmdType, string cmdText, params OleDbParameter[] commandParameters)
        {
            OleDbCommand cmd = new OleDbCommand();
            OleDbConnection conn = new OleDbConnection(ConnString);

            // we use a try/catch here because if the method throws an exception we want to 
            // close the connection throw code, because no datareader will exist, hence the 
            // commandBehaviour.CloseConnection will not work
            try
            {
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                OleDbDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Parameters.Clear();
                return rdr;
            }
            catch (Exception e)
            {
                conn.Close(); 
                return null;
            }
        }

        /// <summary>
        /// 获取数据集 [DataSet]
        /// </summary>
        /// <param name="connectionString">数据库连接串</param>
        /// <param name="cmdType">命令类型</param>
        /// <param name="cmdText">SQL语句</param>
        /// <param name="commandParameters">命令参数</param>
        /// <returns>数据集</returns>
        public static DataSet ExecuteDataSet(string connectionString, CommandType cmdType, string cmdText, params OleDbParameter[] commandParameters)
        {
            OleDbDataAdapter adp = new OleDbDataAdapter();
            OleDbCommand cmd = new OleDbCommand();
            OleDbConnection conn = new OleDbConnection(connectionString);

            // we use a try/catch here because if the method throws an exception we want to 
            // close the connection throw code, because no datareader will exist, hence the 
            // commandBehaviour.CloseConnection will not work
            try
            {
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                adp.SelectCommand = cmd;
                DataSet ds = new DataSet();
                adp.Fill(ds);
                cmd.Parameters.Clear();
                return ds;
            }
            catch (Exception e)
            {
                conn.Close(); 
                return new DataSet();
            }
            finally
            {
                conn.Close();
            }
        }

        /// <summary>
        /// 获取数据集 [DataSet]
        /// </summary>
        /// <param name="cmdType">命令类型</param>
        /// <param name="cmdText">SQL语句</param>
        /// <param name="startIndex">开始索引</param>
        /// <param name="pageSize">记录大小</param>
        /// <param name="commandParameters">命令参数</param>
        /// <returns>数据集</returns>
        public static DataSet ExecuteDataSet(CommandType cmdType, string cmdText, int startIndex, int pageSize, params OleDbParameter[] commandParameters)
        {
            OleDbDataAdapter adp = new OleDbDataAdapter();
            OleDbCommand cmd = new OleDbCommand();
            OleDbConnection conn = new OleDbConnection(AccessHelper.ConnString);

            // we use a try/catch here because if the method throws an exception we want to 
            // close the connection throw code, because no datareader will exist, hence the 
            // commandBehaviour.CloseConnection will not work
            try
            {
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                adp.SelectCommand = cmd;
                DataSet ds = new DataSet();
                adp.Fill(ds, startIndex, pageSize, "T");
                cmd.Parameters.Clear();
                return ds;
            }
            catch (Exception e)
            {
                conn.Close(); 
                return new DataSet();
            }
            finally
            {
                conn.Close();
            }
        }

        /// <summary>
        /// 获取数据集 [DataSet]
        /// </summary>
        /// <param name="cmdType">命令类型</param>
        /// <param name="cmdText">SQL语句</param>
        /// <param name="commandParameters">命令参数</param>
        /// <returns>数据集</returns>
        public static DataSet ExecuteDataSet(CommandType cmdType, string cmdText, params OleDbParameter[] commandParameters)
        {
            return ExecuteDataSet(ConnString, cmdType, cmdText, commandParameters);
        }

        #endregion

        #region 缓存参数
        /// <summary>
        /// add parameter array to the cache
        /// </summary>
        /// <param name="cacheKey">Key to the parameter cache</param>
        /// <param name="cmdParms">an array of SqlParamters to be cached</param>
        public static void CacheParameters(string cacheKey, params OleDbParameter[] commandParameters)
        {
            parmCache[cacheKey] = commandParameters;
        }

        /// <summary>
        /// Retrieve cached parameters
        /// </summary>
        /// <param name="cacheKey">key used to lookup parameters</param>
        /// <returns>Cached SqlParamters array</returns>
        public static OleDbParameter[] GetCachedParameters(string cacheKey)
        {
            OleDbParameter[] cachedParms = (OleDbParameter[])parmCache[cacheKey];

            if (cachedParms == null)
                return null;

            OleDbParameter[] clonedParms = new OleDbParameter[cachedParms.Length];

            for (int i = 0, j = cachedParms.Length; i < j; i++)
                clonedParms[i] = (OleDbParameter)((ICloneable)cachedParms[i]).Clone();

            return clonedParms;
        }
        #endregion

        #region 加载执行命令
        /// <summary>
        /// 加载执行命令
        /// </summary>
        /// <param name="cmd"></param>
        /// <param name="conn"></param>
        /// <param name="trans"></param>
        /// <param name="cmdType"></param>
        /// <param name="cmdText"></param>
        /// <param name="cmdParms"></param>
        private static void PrepareCommand(OleDbCommand cmd, OleDbConnection conn, OleDbTransaction trans, CommandType cmdType, string cmdText, OleDbParameter[] cmdParms)
        {
            if (conn.State != ConnectionState.Open)
                conn.Open();

            cmd.Connection = conn;
            cmd.CommandText = cmdText;

            if (trans != null)
                cmd.Transaction = trans;

            cmd.CommandType = cmdType;

            if (cmdParms != null)
            {
                foreach (OleDbParameter parm in cmdParms)
                    cmd.Parameters.Add(parm);
            }
        }
        #endregion
    }
}
